// 引入配置文件
document.write('<script src="js/config.js"></script>');

$(document).ready(function() {
    // 检查是否已登录
    if (!checkAuth()) return;
    
    // 初始化变量
    let currentNoteId = null;
    let isEditing = false;
    
    // 我的笔记分页
    let myNotesPage = 1;
    let myNotesSize = 10;
    let myNotesKeyword = '';
    let myNotesTotalPages = 1;
    
    // 共享笔记分页
    let sharedNotesPage = 1;
    let sharedNotesSize = 10;
    let sharedNotesKeyword = '';
    let sharedNotesTotalPages = 1;
    
    // 显示用户信息
    const userInfo = getUserInfo();
    $('#username').text(userInfo.username);
    
    // 初始化加载数据
    loadMyNotes();
    
    // 标签切换
    $('.tab').click(function() {
        const tabId = $(this).data('tab');
        
        // 切换标签激活状态
        $('.tab').removeClass('active');
        $(this).addClass('active');
        
        // 切换内容显示
        $('.tab-pane').removeClass('active');
        $(`#${tabId}`).addClass('active');
        
        // 加载相应数据
        if (tabId === 'my-notes') {
            loadMyNotes();
        } else if (tabId === 'shared-notes') {
            loadSharedNotes();
        }
    });
    
    // 退出登录
    $('#logout-btn').click(function() {
        removeToken();
        removeUserInfo();
        window.location.href = 'index.html';
    });
    
    // 新建笔记按钮点击
    $('#new-note-btn').click(function() {
        openNoteModal();
    });
    
    // 取消按钮点击
    $('#cancel-btn').click(function() {
        closeNoteModal();
    });
    
    // 模态框关闭按钮点击
    $('.close').click(function() {
        closeNoteModal();
        closeViewNoteModal();
    });
    
    // 笔记表单提交
    $('#note-form').submit(function(e) {
        e.preventDefault();
        
        const noteId = $('#note-id').val();
        const title = $('#note-title').val().trim();
        const content = $('#note-content').val().trim();
        const shared = $('#note-shared').is(':checked');
        
        if (!title) {
            alert('标题不能为空');
            return;
        }
        
        if (!content) {
            alert('内容不能为空');
            return;
        }
        
        const noteData = {
            title,
            content,
            shared
        };
        
        let apiUrl, method;
        
        if (isEditing && noteId) {
            // 更新笔记
            apiUrl = `/note/${noteId}`;
            method = 'PUT';
        } else {
            // 创建笔记
            apiUrl = '/note';
            method = 'POST';
        }
        
        apiRequest(apiUrl, method, noteData)
            .then(data => {
                closeNoteModal();
                loadMyNotes();
                alert(isEditing ? '笔记更新成功' : '笔记创建成功');
            })
            .catch(error => {
                alert(error.message || '操作失败，请稍后再试');
            });
    });
    
    // 我的笔记搜索
    $('#my-notes-search-btn').click(function() {
        myNotesKeyword = $('#my-notes-search').val().trim();
        myNotesPage = 1;
        loadMyNotes();
    });
    
    // 共享笔记搜索
    $('#shared-notes-search-btn').click(function() {
        sharedNotesKeyword = $('#shared-notes-search').val().trim();
        sharedNotesPage = 1;
        loadSharedNotes();
    });
    
    // 我的笔记分页按钮
    $('#my-notes-prev').click(function() {
        if (myNotesPage > 1) {
            myNotesPage--;
            loadMyNotes();
        }
    });
    
    $('#my-notes-next').click(function() {
        if (myNotesPage < myNotesTotalPages) {
            myNotesPage++;
            loadMyNotes();
        }
    });
    
    // 共享笔记分页按钮
    $('#shared-notes-prev').click(function() {
        if (sharedNotesPage > 1) {
            sharedNotesPage--;
            loadSharedNotes();
        }
    });
    
    $('#shared-notes-next').click(function() {
        if (sharedNotesPage < sharedNotesTotalPages) {
            sharedNotesPage++;
            loadSharedNotes();
        }
    });
    
    // 编辑笔记按钮点击
    $(document).on('click', '#edit-note-btn', function() {
        const noteId = $(this).data('id');
        
        apiRequest(`/note/${noteId}`, 'GET')
            .then(note => {
                closeViewNoteModal();
                openNoteModal(note);
            })
            .catch(error => {
                alert(error.message || '获取笔记详情失败');
            });
    });
    
    // 删除笔记按钮点击
    $(document).on('click', '#delete-note-btn', function() {
        const noteId = $(this).data('id');
        
        if (confirm('确定要删除这篇笔记吗？此操作不可恢复。')) {
            apiRequest(`/note/${noteId}`, 'DELETE')
                .then(data => {
                    closeViewNoteModal();
                    loadMyNotes();
                    alert('笔记删除成功');
                })
                .catch(error => {
                    alert(error.message || '删除失败，请稍后再试');
                });
        }
    });
    
    // 切换共享状态按钮点击
    $(document).on('click', '#toggle-share-btn', function() {
        const noteId = $(this).data('id');
        
        apiRequest(`/note/${noteId}/toggle-sharing`, 'POST')
            .then(note => {
                closeViewNoteModal();
                loadMyNotes();
                alert(`笔记已${note.shared ? '设为共享' : '设为私有'}`);
            })
            .catch(error => {
                alert(error.message || '操作失败，请稍后再试');
            });
    });
    
    // 点击笔记项查看详情
    $(document).on('click', '.note-item', function() {
        const noteId = $(this).data('id');
        const isOwner = $(this).data('is-owner');
        
        apiRequest(`/note/${noteId}`, 'GET')
            .then(note => {
                openViewNoteModal(note, isOwner);
            })
            .catch(error => {
                alert(error.message || '获取笔记详情失败');
            });
    });
    
    // 加载我的笔记
    function loadMyNotes() {
        const params = `page=${myNotesPage}&size=${myNotesSize}${myNotesKeyword ? `&keyword=${encodeURIComponent(myNotesKeyword)}` : ''}`;
        
        apiRequest(`/note/my?${params}`, 'GET')
            .then(data => {
                renderNotesList('#my-notes-list', data.records, true);
                
                // 更新分页信息
                myNotesTotalPages = data.totalPages;
                $('#my-notes-current-page').text(myNotesPage);
                $('#my-notes-total-pages').text(myNotesTotalPages);
                
                // 更新分页按钮状态
                $('#my-notes-prev').prop('disabled', myNotesPage <= 1);
                $('#my-notes-next').prop('disabled', myNotesPage >= myNotesTotalPages);
            })
            .catch(error => {
                $('#my-notes-list').html(`<div class="error-message">加载失败: ${error.message}</div>`);
            });
    }
    
    // 加载共享笔记
    function loadSharedNotes() {
        const params = `page=${sharedNotesPage}&size=${sharedNotesSize}${sharedNotesKeyword ? `&keyword=${encodeURIComponent(sharedNotesKeyword)}` : ''}`;
        
        apiRequest(`/note/shared?${params}`, 'GET', null, false)
            .then(data => {
                renderNotesList('#shared-notes-list', data.records, false);
                
                // 更新分页信息
                sharedNotesTotalPages = data.totalPages;
                $('#shared-notes-current-page').text(sharedNotesPage);
                $('#shared-notes-total-pages').text(sharedNotesTotalPages);
                
                // 更新分页按钮状态
                $('#shared-notes-prev').prop('disabled', sharedNotesPage <= 1);
                $('#shared-notes-next').prop('disabled', sharedNotesPage >= sharedNotesTotalPages);
            })
            .catch(error => {
                $('#shared-notes-list').html(`<div class="error-message">加载失败: ${error.message}</div>`);
            });
    }
    
    // 渲染笔记列表
    function renderNotesList(selector, notes, isOwner) {
        const $container = $(selector);
        
        if (!notes || notes.length === 0) {
            $container.html('<div class="empty-message">暂无笔记</div>');
            return;
        }
        
        let html = '';
        
        notes.forEach(note => {
            html += `
                <div class="note-item" data-id="${note.id}" data-is-owner="${isOwner}">
                    <h3>${note.title}</h3>
                    <p class="note-preview">${truncateText(note.content, 100)}</p>
                    <div class="note-meta">
                        <span>作者: ${note.ownerName}</span>
                        <span>更新时间: ${formatDateTime(note.updateTime)}</span>
                        <span>状态: ${note.shared ? '共享' : '私有'}</span>
                    </div>
                </div>
            `;
        });
        
        $container.html(html);
    }
    
    // 打开笔记编辑模态框
    function openNoteModal(note = null) {
        // 重置表单
        $('#note-form')[0].reset();
        $('#note-id').val('');
        
        if (note) {
            // 编辑模式
            $('#modal-title').text('编辑笔记');
            $('#note-id').val(note.id);
            $('#note-title').val(note.title);
            $('#note-content').val(note.content);
            $('#note-shared').prop('checked', note.shared);
            
            currentNoteId = note.id;
            isEditing = true;
        } else {
            // 新建模式
            $('#modal-title').text('新建笔记');
            currentNoteId = null;
            isEditing = false;
        }
        
        $('#note-modal').css('display', 'block');
    }
    
    // 关闭笔记编辑模态框
    function closeNoteModal() {
        $('#note-modal').css('display', 'none');
    }
    
    // 打开笔记查看模态框
    function openViewNoteModal(note, isOwner) {
        $('#view-note-title').text(note.title);
        $('#view-note-content').text(note.content);
        $('#view-note-owner').text(note.ownerName);
        $('#view-note-create-time').text(formatDateTime(note.createTime));
        $('#view-note-update-time').text(formatDateTime(note.updateTime));
        $('#view-note-shared').text(note.shared ? '共享' : '私有');
        
        // 设置操作按钮
        if (isOwner) {
            $('#view-note-actions').show();
            $('#edit-note-btn').data('id', note.id);
            $('#delete-note-btn').data('id', note.id);
            $('#toggle-share-btn').data('id', note.id);
            $('#toggle-share-btn').text(note.shared ? '设为私有' : '设为共享');
        } else {
            $('#view-note-actions').hide();
        }
        
        $('#view-note-modal').css('display', 'block');
    }
    
    // 关闭笔记查看模态框
    function closeViewNoteModal() {
        $('#view-note-modal').css('display', 'none');
    }
    
    // 文本截断函数
    function truncateText(text, maxLength) {
        if (!text) return '';
        if (text.length <= maxLength) return text;
        return text.substring(0, maxLength) + '...';
    }
});
